const express = require('express');
const uuid = require('uuid');
const {
	Msg,
	Paths
} = require('../tools/message.js');
const mysqlObj = require('../model/mysql.class.js');
const router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
	res.send('respond with a resource');
});


router.post('/register', async function(req, res, next) {

	let username = req.body.uname ? req.body.uname : "";

	let {
		username: uname,
		psw,
		submit
	} = req.body;


	console.log(username, psw, submit);

	let unameReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

	if (!unameReg.test(username)) {
		res.send(Msg(200, '用户名不合法'));
		return;
	}

	let sql = `SELECT COUNT(*) AS n FROM member WHERE username='${username}'`;
	let [err, arr] = await mysqlObj.exec(sql);


	if (arr[0].n != 0) {
		res.send(Msg(200, '用户名已经注册'));
		return
	}
	res.send(Msg(200, '用户名可以使用'));


	if (submit) {
		sql =
			`insert into member(uid,username,password,head_photo_url,createdate) values('${uuid.v1()}','${username}','${psw}','image_source/head_photo/head_01.png','${new Date().getTime()}')`;

		console.log(sql);
		[err, arr] = await mysqlObj.exec(sql);

		if (!err) {
			res.send('注册成功');
		}
	}
});


router.post('/login', async function(req, res) {
	let {
		uname,
		psw
	} = req.body;


	let sql = `SELECT COUNT(*) AS n, password AS p FROM member WHERE username='${uname}'`;
	let [err, arr] = await mysqlObj.exec(sql);

	if (arr[0].n = 0) {
		res.send('账号错误');
		return;
	}

	if (arr[0].p == psw) {
		res.send('登录成功');
		return
	}

	res.send('密码错误');

	// sql = `SELECT COUNT(*) FROM member WHERE username='${uname}'`;
	// [err, arr] = await mysqlObj.exec(sql);

	// console.log(uname,psw);
})

module.exports = router;
